<?php

namespace app\api\model;

use app\common\enums\StatusEnum;

class LangClassRecite extends \app\common\model\LangClassRecite
{
    /**
     * 获取课程类型所有的单词或者句子 和 答案
     * @param $oauthId
     * @param $classId
     * @param $courseType int 课程类型，1语音课，2基础课，3高级课
     * @param $type int 背诵类型
     * @param $typeId int 分类
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getList($oauthId, $classId, $courseType, $type, $typeId)
    {
        // 判断是否已经购买
        $buyLog = OauthOrderClass::getOneByClass($oauthId, $classId);
        if (empty($buyLog)) {
            return [
                'isBuy' => false,
            ];
        }

        // 查找班级对应的所有单词或者句子
        $sql = static::field('id AS reciteId, class_id AS classId, word, file,size,create_time')
            ->where([
                'class_id' => $classId,
                'course_type' => $courseType,
                'type' => $type,
                'type_id' => $typeId,
                'status' => StatusEnum::ENABLED
            ]);

        $recite = $sql->order(['sort_num' => 'desc', 'create_time' => 'desc'])
            ->select()
            ->toArray();
        if (empty($recite)) {
            return [];
        }

        $reciteIds = [];
        foreach ($recite as $key => $value) {
            $recite[$key]['create_time'] = date('Y-m-d H:i:s',$value['create_time']);
            $recite[$key]['file'] = config('file_prefix') . $value['file'];
            $reciteIds[$value['reciteId']] = $value['reciteId'];
        }

        if ($reciteIds) {
            // 获取收藏列表
            $collect = OauthRecite::getListByTypeColumn($oauthId, OauthRecite::TYPE_COLLECT, $reciteIds);
            // 单词或句子对应的答案
            $answers = LangClassReciteAnswer::getListByRecite($reciteIds);
            foreach ($recite as $key => $value) {
                $recite[$key]['isCollect'] = isset($collect[$value['reciteId']]) ? 1 : 0;
                $recite[$key]['answers'] = isset($answers[$value['reciteId']]) ? $answers[$value['reciteId']] : [];
            }
        }

        return [
            'list' => $recite,
            'count' => $sql->count()
        ];
    }

    /**
     * 通过ID找数据
     * @param $ids
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getByIds($ids)
    {
        return static::field('id AS reciteId, class_id AS classId')
            ->where('id', 'in', $ids)
            ->where(['status' => StatusEnum::ENABLED])
            ->select()
            ->column('classId', 'reciteId');
    }
}